package com.dxy.df.utils;


import com.alibaba.fastjson.JSONObject;
import com.dxy.df.constants.ConstNumbers;
import com.dxy.df.constants.ConstStrings;
import com.dxy.df.core.model.BasicEntity;
import com.dxy.df.core.model.BasicInput;
import com.dxy.df.core.shiro.ShiroUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * @author admin
 * @date 2018/3/17 上午10:18
 */
public class UcBeanUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(UcBeanUtils.class);

    public static Map<String, Object> beanToMapBySnakeCase(Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setPropertyNamingStrategy(com.fasterxml.jackson.databind.PropertyNamingStrategy.SNAKE_CASE);
        try {
            String json = mapper.writeValueAsString(obj);
            JSONObject jsonObject = JSONObject.parseObject(json);
            JSONObject data = new JSONObject();
            jsonObject.forEach((k, v) -> {
                if (null != v) {
                    data.put(k, v);
                }
            });
            return data;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static <T> T mapToObject(Map<String, Object> map, Class<T> beanClass) throws Exception {
        if (map == null) {
            return null;
        }
        T obj = beanClass.newInstance();
        BeanUtils.populate(obj, map);
        return obj;
    }


    public static <T extends BasicEntity> T copyPropertiesForDDL(BasicInput source, Class<T> clazz, String type) {
        try {
            BasicEntity target = clazz.newInstance();
            org.springframework.beans.BeanUtils.copyProperties(source, target);
            String userAccount= ShiroUtils.getUserAccount();
            if (null == target.getUpdateBy()) {
                target.setUpdateBy(userAccount);
            }

            if (ConstStrings.ADD.equals(type)) {
                if (null == target.getCreateBy()) {
                    target.setCreateBy(userAccount);
                }
                if (null == target.getCreateBy()) {
                    target.setCreateBy(userAccount);
                }
                target.setRecordStatus(ConstNumbers.OK);
            }
            return (T) target;
        } catch (Exception e) {
            LOGGER.info(e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

}
